package cn.edu.scau.serviceImpl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.scau.dao.ArticleDao;
import cn.edu.scau.daoImpl.ArticleDaoImpl;
import cn.edu.scau.entity.Article;
import cn.edu.scau.entity.Work;
import cn.edu.scau.service.ArticleService;

@Service("articleServiceImpl")
public class ArticleServiceImpl implements ArticleService {
	//文章接口实例
	@Resource(name="articleDaoImpl")
	private ArticleDao articleDao;
	//随机数类
	Random random = new Random();

	/**
	 * 添加文章
	 * @param article 新的文章类
	 */
	@Override
	public void add(Article article) {
		articleDao.save(article);
	}
	/**
	 * 根据id删除文章
	 * @param id 需要删除文章的id
	 */
	@Override
	public boolean delete(Integer id) {
		Article article = articleDao.find(Article.class, id);
		if(article==null){
			return false;
		}else{
			articleDao.delete(Article.class, id);
			return true;
		}
		
	}
	
	/**
	 * 更新文章信息
	 * @param newArticle 更新后的文章
	 * @param id 需要更新的文章的id
	 */
	@Override
	public boolean update(Article newArticle, Integer id) {
		Article article = articleDao.find(Article.class, id);
		if(article==null){
			return false;
		}else{
			if(newArticle.getAuthor()!=null){
				article.setAuthor(newArticle.getAuthor());
			}
			if(newArticle.getColumnId()!=null){
				article.setColumnId(newArticle.getColumnId());
			}
			if(newArticle.getContent()!=null){
				article.setContent(newArticle.getContent());
			}
			if(newArticle.getEditor()!=null){
				article.setEditor(newArticle.getEditor());
			}
			if(newArticle.getLikeTimes()!=null){
				article.setLikeTimes(newArticle.getLikeTimes());
			}
			if(newArticle.getReleaseDate()!=null){
				article.setReleaseDate(newArticle.getReleaseDate());
			}
			if(newArticle.getSource()!=null){
				article.setSource(newArticle.getSource());
			}
			if(newArticle.getTitle()!=null){
				article.setTitle(newArticle.getTitle());
			}
			if(newArticle.isStatus()){
				article.setStatus(true);
			}else{
				article.setStatus(false);
			}
			articleDao.update(article);
			return true;
		}
	
	}
	/**
	 * 根据文章id获取文章
	 * @param id 文章的id
	 * @return 文章
	 */
	@Override
	public Article showArticleByID(Integer id) {
		return articleDao.find(Article.class, id);
	}
	
	/**
	 * 根据栏目的id来展示所有文章
	 * @param columnId 栏目的id
	 * @param pageNo 页数
	 * @param pageSize 一页展示的最大条数
	 * @return 文章集合
	 */
	@Override
	public List<Article> showArticlesByColumnId(Integer columnId, Integer pageNo, Integer pageSize,boolean frontOrBackground) {
		return articleDao.showArticleByColumnId(columnId, pageNo, pageSize,frontOrBackground);
	}
	/**
	 * 根据栏目id展示推荐内容，推荐内容为点赞次数前几
	 * @param columnId 栏目的id
	 * @param pageSize 点赞次数前几
	 * @return 文章集合
	 */
	@Override
	public List<Article> showTheRecommendArticleByColumnId(Integer columnId, Integer pageSize) {
		return articleDao.showTheRecommendArticleByColumnId(columnId, pageSize);
	}
	/**
	 * 根据栏目id返回页数的总量
	 * @param coulumnId 栏目的id
	 * @param pageSize 一页展示的最大条数
	 * @return 页数
	 */
	public long countTheEntityNum(Integer columnId,Integer pageSize,boolean frontOrBackground) {
		
		long articleNum = articleDao.countArticleNumByColumnId(columnId,frontOrBackground);
		if(articleNum%pageSize==0){
			return articleNum/pageSize;
		}else{
			return articleNum/pageSize+1;
		}
	}
	
	
	
	public List<String> saveImage(MultipartFile[] files, HttpServletRequest request, String releaseDate) {

		// 新建集合,用于保存文件路径和名称
		List<String> images = new ArrayList<>();
		// 获得顶级文件夹路径
		String path = request.getSession().getServletContext().getRealPath("/Upload/");
		// 获取纯数字的日期
		String date = getDate(releaseDate, 2);
		// 组合文件夹的名称
		String dirName = "day_" + date;
		// 循环保存上传的文件
		for (int i = 0; i < files.length; i++) {

			// 文件的后缀名称
			String suffix = files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf('.'));

			System.out.println(suffix);
			// 组合图像的名称
			String fileName = date + this.getRandomString(10) + suffix;
			// 将图片保存路径放到集合中
			images.add("/Upload/" + dirName + "/" + fileName);
			// 新建一个文件
			File targetFile = new File(path + dirName + "/", fileName);
			// 如果文件夹不存在，则新建文件夹
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存人物头像
			try {
				files[i].transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return images;

	}
	/**
	 * 根据日期，获取保存文件夹的名字
	 *
	 * @return
	 */
	public String getDate(String releaseDate, int start) {

		char[] chs = releaseDate.toCharArray();
		StringBuilder builder = new StringBuilder();

		for (int i = start; i < chs.length; i++) {

			if (chs[i] == ' ') {
				break;
			}

			if (chs[i] >= '0' && chs[i] <= '9') {
				builder.append(chs[i]);
			}
		}
		return new String(builder);
	}
	/**
	 * 获取随机字符串，用于组成图片的名字
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "012345678901234567890123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
	
	public ArticleDao getArticleDao() {
		return articleDao;
	}
	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}
	@Override
	public List showTheEntity(String type, Integer columnId, Integer id, Integer pageNo, boolean frontOrBackground) {
		// TODO Auto-generated method stub
		return null;
	}
}
